package com.my.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.*;
import java.util.EnumSet;

//相当于web.xml
public class WebConfigInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        //1.创建Spring MVC servlet IOC容器
        AnnotationConfigWebApplicationContext servletApplicationContext = new AnnotationConfigWebApplicationContext();
        servletApplicationContext.register(SpringMvcConfig.class);//注册配置类
        servletApplicationContext.setServletContext(servletContext);

        //2.创建前端控制器，同时加载IOC容器
        DispatcherServlet dispatcherServlet = new DispatcherServlet(servletApplicationContext);
        //3.注册前端控制器到tomcat的servlet容器中
        ServletRegistration.Dynamic dispatcherServletRegistration =
                servletContext.addServlet("dispatcherServlet", dispatcherServlet);
        //4.设置前端控制器随tomcat启动而创建
        dispatcherServletRegistration.setLoadOnStartup(1);
        //5.设置前端控制器拦截所有请求路径
        dispatcherServletRegistration.addMapping("/");

        //6.创建字符编码过滤器
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        FilterRegistration.Dynamic characterEncodingFilterRegistration =
                servletContext.addFilter("characterEncodingFilter", characterEncodingFilter);
        //7.设置初始参数和拦截路径
        characterEncodingFilterRegistration.setInitParameter("encoding", "UTF-8");
        characterEncodingFilterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),
                false, "/*");

        //8.创建Spring Root IOC容器
        AnnotationConfigWebApplicationContext rootApplicationContext = new AnnotationConfigWebApplicationContext();
        rootApplicationContext.register(SpringConfig.class);
        rootApplicationContext.setServletContext(servletContext);
        //8.Spring监听器
        ContextLoaderListener contextLoaderListener = new ContextLoaderListener(rootApplicationContext);
        servletContext.addListener(contextLoaderListener);
//        servletContext.setInitParameter("contextInitializerClasses", "com.my.config.SpringConfig");
    }

}
